import React, { useState, useEffect } from "react";
import { Modal, Form, Input, Select, message, Button, Tag } from "antd";
import { PlusOutlined, DeleteOutlined } from "@ant-design/icons";
import { useAppDispatch } from "../../../hooks/redux";
import { updateProject, createGroup, updateGroup, deleteGroup, fetchProjects } from "../../../store/projectSlice";
import { mockProjectApi } from "../../../api/mockProjectApi";
import type { User, Project } from "../../../types/project";

const { TextArea } = Input;
const { Option } = Select;

interface EditProjectModalProps {
  /** 弹窗是否可见 */
  visible: boolean;
  /** 取消回调 */
  onCancel: () => void;
  /** 成功保存回调 */
  onSuccess: () => void;
  /** 要编辑的项目 */
  project: Project;
}

/**
 * 编辑项目弹窗组件
 * 提供表单让用户修改项目信息和管理分组
 */
const EditProjectModal: React.FC<EditProjectModalProps> = ({ visible, onCancel, onSuccess, project }) => {
  const dispatch = useAppDispatch();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [users, setUsers] = useState<User[]>([]);
  const [groups, setGroups] = useState<
    Array<{ id?: string; title: string; color: string; order?: number; isNew?: boolean }>
  >([]);

  /**
   * 获取用户列表并初始化表单
   */
  useEffect(() => {
    const fetchUsers = async () => {
      try {
        const userList = await mockProjectApi.getUsers();
        setUsers(userList);
      } catch (error) {
        console.error("获取用户列表失败:", error);
      }
    };

    if (visible && project) {
      fetchUsers();

      // 初始化表单数据
      form.setFieldsValue({
        title: project.title,
        description: project.description,
        creatorId: project.creator.id,
        memberIds: project.members.map(m => m.id)
      });

      // 初始化分组数据
      setGroups(
        project.groups.map(group => ({
          id: group.id,
          title: group.title,
          color: group.color || "#f5f5f5",
          order: group.order,
          isNew: false
        }))
      );
    }
  }, [visible, project, form]);

  /**
   * 处理表单提交
   * @param values 表单数据
   */
  const handleSubmit = async (values: {
    title: string;
    description: string;
    creatorId: string;
    memberIds: string[];
  }) => {
    setLoading(true);
    try {
      // 新增分组必填校验
      const invalidNewGroups = groups.filter(g => g.isNew && !g.title.trim());
      if (invalidNewGroups.length > 0) {
        message.warning("请为新增分组填写名称");
        setLoading(false);
        return;
      }

      // 更新项目基本信息
      const projectData = {
        title: values.title,
        description: values.description,
        creator: users.find(u => u.id === values.creatorId) || project.creator,
        members:
          values.memberIds
            ?.map((id: string) => users.find(u => u.id === id))
            .filter((user): user is User => Boolean(user)) || []
      };

      await dispatch(
        updateProject({
          projectId: project.id,
          data: projectData
        })
      ).unwrap();

      // 处理分组更新
      await updateProjectGroups();

      // 刷新项目列表，确保看板立即显示最新分组
      await dispatch(fetchProjects()).unwrap();

      message.success("项目更新成功");
      onSuccess();
    } catch (error) {
      console.error("更新项目失败:", error);
      message.error("更新项目失败，请重试");
    } finally {
      setLoading(false);
    }
  };

  /**
   * 更新项目分组
   */
  const updateProjectGroups = async () => {
    const existingGroups = project.groups;
    const currentGroups = groups.filter(g => g.title.trim());

    // 处理新增的分组
    for (const group of currentGroups.filter(g => g.isNew)) {
      await dispatch(
        createGroup({
          projectId: project.id,
          groupData: {
            title: group.title,
            color: group.color,
            order: group.order || 0
          }
        })
      ).unwrap();
    }

    // 处理更新的分组
    for (const group of currentGroups.filter(g => !g.isNew && g.id)) {
      const existingGroup = existingGroups.find(eg => eg.id === group.id);
      if (existingGroup && (existingGroup.title !== group.title || existingGroup.color !== group.color)) {
        await dispatch(
          updateGroup({
            projectId: project.id,
            groupId: group.id!,
            data: {
              title: group.title,
              color: group.color
            }
          })
        ).unwrap();
      }
    }

    // 处理删除的分组
    const currentGroupIds = currentGroups.filter(g => g.id).map(g => g.id);
    for (const existingGroup of existingGroups) {
      if (!currentGroupIds.includes(existingGroup.id)) {
        await dispatch(
          deleteGroup({
            projectId: project.id,
            groupId: existingGroup.id
          })
        ).unwrap();
      }
    }
  };

  /**
   * 处理弹窗关闭
   */
  const handleCancel = () => {
    form.resetFields();
    setGroups([]);
    onCancel();
  };

  /**
   * 添加分组
   */
  const addGroup = () => {
    const newGroup = {
      title: "",
      color: "#f5f5f5",
      order: groups.length,
      isNew: true
    };
    setGroups([...groups, newGroup]);
  };

  /**
   * 删除分组
   */
  const removeGroup = (index: number) => {
    if (groups.length <= 1) {
      message.warning("至少需要保留一个分组");
      return;
    }

    const group = groups[index];
    if (!group.isNew && group.id) {
      // 检查分组是否有任务
      const existingGroup = project.groups.find(g => g.id === group.id);
      if (existingGroup && existingGroup.tasks.length > 0) {
        message.warning(`分组"${group.title}"中还有 ${existingGroup.tasks.length} 个任务，请先移动或删除这些任务`);
        return;
      }
    }

    const newGroups = groups.filter((_, i) => i !== index);
    setGroups(newGroups);
  };

  /**
   * 更新分组
   */
  const updateGroupLocal = (index: number, field: string, value: string) => {
    const newGroups = [...groups];
    newGroups[index] = { ...newGroups[index], [field]: value };
    setGroups(newGroups);
  };

  /**
   * 预定义颜色选项
   */
  const colorOptions = [
    "#f5f5f5",
    "#1890ff",
    "#52c41a",
    "#faad14",
    "#f5222d",
    "#722ed1",
    "#13c2c2",
    "#eb2f96",
    "#fa541c",
    "#a0d911"
  ];

  return (
    <Modal
      title="编辑项目"
      open={visible}
      onCancel={handleCancel}
      onOk={() => form.submit()}
      confirmLoading={loading}
      okText="保存更改"
      cancelText="取消"
      width={700}
      destroyOnClose
    >
      <Form form={form} layout="vertical" onFinish={handleSubmit}>
        {/* 项目标题 */}
        <Form.Item
          name="title"
          label="项目标题"
          rules={[
            { required: true, message: "请输入项目标题" },
            { max: 100, message: "标题不能超过100个字符" }
          ]}
        >
          <Input placeholder="请输入项目标题" />
        </Form.Item>

        {/* 项目描述 */}
        <Form.Item name="description" label="项目描述" rules={[{ max: 500, message: "描述不能超过500个字符" }]}>
          <TextArea placeholder="请输入项目描述（可选）" rows={3} showCount maxLength={500} />
        </Form.Item>

        {/* 负责人和参与人 */}
        <div className="flex gap-4">
          {/* 项目负责人 */}
          <Form.Item
            name="creatorId"
            label="项目负责人"
            className="flex-1"
            rules={[{ required: true, message: "请选择项目负责人" }]}
          >
            <Select placeholder="请选择负责人">
              {users.map(user => (
                <Option key={user.id} value={user.id}>
                  <div className="flex items-center gap-2">
                    <img src={user.avatar} alt={user.name} className="w-4 h-4 rounded-full" />
                    {user.name}
                  </div>
                </Option>
              ))}
            </Select>
          </Form.Item>

          {/* 参与人 */}
          <Form.Item name="memberIds" label="项目参与人" className="flex-1">
            <Select mode="multiple" placeholder="请选择参与人" allowClear maxTagCount={3}>
              {users.map(user => (
                <Option key={user.id} value={user.id}>
                  <div className="flex items-center gap-2">
                    <img src={user.avatar} alt={user.name} className="w-4 h-4 rounded-full" />
                    {user.name}
                  </div>
                </Option>
              ))}
            </Select>
          </Form.Item>
        </div>

        {/* 任务分组管理 */}
        <Form.Item label="任务分组管理">
          <div className="space-y-3">
            {groups.map((group, index) => (
              <div key={group.id || index} className="flex items-center gap-3 p-3 border border-gray-200 rounded-lg">
                <Input
                  placeholder="分组名称"
                  value={group.title}
                  onChange={e => updateGroupLocal(index, "title", e.target.value)}
                  className="flex-1"
                />
                <Select
                  value={group.color}
                  onChange={value => updateGroupLocal(index, "color", value)}
                  className="w-32"
                  dropdownRender={menu => (
                    <div>
                      {menu}
                      <div className="grid grid-cols-5 gap-2 p-2 border-t">
                        {colorOptions.map(color => (
                          <div
                            key={color}
                            className="w-6 h-6 rounded-full cursor-pointer border border-gray-200 hover:scale-110 transition-transform"
                            style={{ backgroundColor: color }}
                            onClick={() => updateGroupLocal(index, "color", color)}
                          />
                        ))}
                      </div>
                    </div>
                  )}
                >
                  <Option value={group.color}>
                    <div className="flex items-center gap-2">
                      <div className="w-4 h-4 rounded-full" style={{ backgroundColor: group.color }} />
                      颜色
                    </div>
                  </Option>
                </Select>

                {/* 显示任务数量 */}
                {!group.isNew && group.id && (
                  <Tag color="blue" className="ml-2">
                    {project.groups.find(g => g.id === group.id)?.tasks.length || 0} 个任务
                  </Tag>
                )}

                <Button
                  type="text"
                  icon={<DeleteOutlined />}
                  onClick={() => removeGroup(index)}
                  disabled={groups.length <= 1}
                  className="text-red-500 hover:text-red-700"
                />
              </div>
            ))}

            <Button type="dashed" icon={<PlusOutlined />} onClick={addGroup} className="w-full">
              添加分组
            </Button>
          </div>
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default EditProjectModal;
